package controllers

import (
	"encoding/json"
	"fmt"
	"net/http"
	"remote_cmd/utils"

	"remote_cmd/models"
	"remote_cmd/result"

	beego "github.com/beego/beego/v2/server/web"
	"github.com/prometheus/common/log"
)

type LinuxController struct {
	beego.Controller
}

func (c *LinuxController) Login() {
	var linux models.Linux
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &linux)
	if err != nil {
		result.HttpResponse(http.StatusBadRequest, []byte(err.Error()), c.Ctx)
		return
	}
	if linux.Name != models.ROOT {
		result.HttpResponse(http.StatusBadRequest, []byte("Currently only supports the root user to log in"), c.Ctx)
		return
	}
	err = linux.Login()
	if err != nil {
		result.HttpResponse(http.StatusUnauthorized, []byte(err.Error()), c.Ctx)
		return
	}
	result.HttpResponse(http.StatusOK, []byte("Login success"), c.Ctx)
}

func (c *LinuxController) Logout() {
	ip := c.GetString("ip")
	if !utils.IsValidIP(ip) {
		result.HttpResponse(http.StatusBadRequest, []byte("Invalid IP"), c.Ctx)
		return
	}
	log.Infof("valid ip is %s", ip)
	linux, ok := models.LinuxCache[ip]
	if !ok {
		result.HttpResponse(http.StatusNotFound, []byte(fmt.Sprintf("not found login ip:%s", ip)), c.Ctx)
		return
	}
	err := linux.Logout()
	if err != nil {
		log.Errorf("linux[%s] logout error: %v", linux.Ip, err)
		result.HttpResponse(http.StatusUnauthorized, []byte(fmt.Sprintf("ip[%s] logout error: %v", linux.Ip, err)), c.Ctx)
		return
	}
	result.HttpResponse(http.StatusOK, []byte(fmt.Sprintf("ip[%s] logout success", ip)), c.Ctx)
}

func (c *LinuxController) LoginAll() {
	var errMap = make(map[string]error)
	for _, ip := range models.LinuxIps {
		linux, ok := models.LinuxCache[ip]
		if ok {
			continue
		}
		linux = &models.Linux{
			Ip:       ip,
			Name:     models.LinuxName,
			Password: models.LinuxPassword,
		}
		err := linux.Login()
		if err != nil {
			errMap[ip] = err
			continue
		}
		models.LinuxCache[ip] = linux
	}
	if len(errMap) != 0 {
		var errorResult string
		for ip, err := range errMap {
			errorResult += fmt.Sprintf("ip[%s] login error: %v", ip, err)
		}
		result.HttpResponse(http.StatusUnauthorized, []byte(errorResult), c.Ctx)
		return
	}
	result.HttpResponse(http.StatusOK, []byte("All machine login successful"), c.Ctx)
}
